/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.interceptor;

import org.apache.ibatis.aapl.annotation.FieldInjection;
import org.apache.ibatis.aapl.annotation.impl.FieldInjectionStrategy;
import org.apache.ibatis.aapl.reflect.MetaUtils;
import org.apache.ibatis.aapl.registry.MethodRegistry;
import org.apache.ibatis.aapl.registry.SqlMethod;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gu
 * @date 2020/4/7 10:05
 */
public class FieldInjectionProcessor implements ParameterProcessor {

  private final static Logger log = LoggerFactory.getLogger(FieldInjectionProcessor.class);
  private MethodRegistry registry = MethodRegistry.getMethodRegistry();

  private Map<Class<? extends FieldInjectionStrategy>, FieldInjectionStrategy> strategyMap = new HashMap<>(4);

  @Override
  public void process(ParameterHandler handler) {
    Object param = handler.getParameterObject();
    if (param == null) {
      return;
    }
    doProcess(param, handler);
  }

  public void doProcess(Object bean, ParameterHandler handler) {
    if (!checkedHandler(handler)) {
      return;
    }
    SqlMethod sqlMethod = registry.getMethod(((DefaultParameterHandler) handler));
    Method method = sqlMethod.getMethod();
    FieldInjection annotation = method.getAnnotation(FieldInjection.class);
    if (annotation == null) {
      return;
    }
    String[] props = annotation.props();
    Class<? extends FieldInjectionStrategy>[] strategies = annotation.strategies();
    if (props.length != strategies.length) {
      log.error("FieldInjection中的props属性长度({})和strategies属性长度({})不一致，无法一一匹配", props.length, strategies.length);
      return;
    }
    for (int i = 0; i < strategies.length; i++) {
      Class<? extends FieldInjectionStrategy> strategy = strategies[i];
      String prop = props[i];
      FieldInjectionStrategy fieldInjectionStrategy = strategyMap.computeIfAbsent(strategy, k -> {
        try {
          return strategy.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          log.warn("请确保 {} 存在public且参数为空的构造函数！", strategy);
          return null;
        }
      });
      if (fieldInjectionStrategy == null) {
        return;
      }
      MetaObject metaObject = MetaUtils.getMetaObject(bean);
      metaObject.setValue(prop, fieldInjectionStrategy.getValue());
    }
  }

  private boolean checkedHandler(ParameterHandler handler) {
    return handler instanceof ParameterHandler;
  }
}
